#include <iostream>
#include <sys/types.h>      
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>

void Usge(char* proc)
{
    std::cout<<"Usage:\t"<<proc<<" serverip serverport"<<std::endl;
}

int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usge(argv[0]);
        exit(-1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //1.创建流式套接字
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        std::cerr<<"socket error"<<std::endl;
        exit(-2);
    }

    //tcp需要bind，但是不需要显示bind
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    //2.connect
    int n = connect(sockfd,(struct sockaddr*)&server,sizeof(server));
    if(n<0)
    {
        std::cerr<<"connect error"<<std::endl;
        exit(-3);
    }

    while(1)
    {
        std::cout<<"Please Enter#";
        std::string outstring;
        std::getline(std::cin,outstring);

        
        size_t s = send(sockfd,outstring.c_str(),outstring.size(),0);
        if(s>0)
        {
            char buffer[1024];
            //读取服务端返回的数据
            size_t m = recv(sockfd,buffer,sizeof(buffer),0);
            if(m>0)
            {
                std::cout<<buffer<<std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    close(sockfd);//需要关闭sockfd
    return 0;
}